import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.AirlineReservationServiceProxy;
import bean.Flight;
import bean.Journey;
import constants.AirlineReservationServiceConstants;


public class FillPassengerDetailsServlet extends HttpServlet{
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		AirlineReservationServiceProxy proxy = new AirlineReservationServiceProxy(
				AirlineReservationServiceConstants.SERVICE_URL);
	
		long flightId1 = 0;
		long flightId2 = 0;
		try{
			 flightId1 = Long.parseLong(req.getParameter("flight1"));
		
		}catch(Exception ex){
			ex.printStackTrace();
		}
		try{
			flightId2 = Long.parseLong(req.getParameter("flight2"));
		}catch(Exception ex){
			ex.printStackTrace();
		}

		String origin = req.getParameter("origin");
		String destination = req.getParameter("destination");
		String startDate = req.getParameter("startDate");
		String returnDate = req.getParameter("returnDate");
		
		double total = 0;
		
		
		long[] ids = new long[2];
		int i = 0;
		if(flightId1 != 0){
			ids[i] = flightId1;
			i++;
		}
		if(flightId2 != 0){
			ids[i] = flightId2;
		}
		Flight[] flights = proxy.getFlightDetails(ids);
		
		List<Journey> lstJourney = new ArrayList<Journey>();
		
		for(int j=0; j<flights.length; j++){
			Journey journey = new Journey();
			Flight flight = flights[j];
			journey.setFlight(flight);
			if(origin.equalsIgnoreCase(flight.getSource()) || origin.equalsIgnoreCase(flight.getIntermediate())){
				journey.setDateOfJourney(startDate);
				journey.setBoardingPoint(origin);
			}else if(destination.equalsIgnoreCase(flight.getSource()) || destination.equalsIgnoreCase(flight.getIntermediate())){
				journey.setDateOfJourney(returnDate);
				journey.setBoardingPoint(destination);
			}
			journey.setNumSeatsBooked(Integer.parseInt(req.getParameter("numTravelers")));
			
			total = total + (Integer.parseInt(req.getParameter("numTravelers"))*flight.getTicketPrice());
			
			
			lstJourney.add(journey);
			
			
			
		}
		System.out.println("Inside Servlet ---------"+req.getParameter("numTravelers"));
		
		
		HttpSession session = req.getSession();
		
		session.setAttribute("journeyDetails", lstJourney);
		session.setAttribute("numTravelers", req.getParameter("numTravelers"));
		session.setAttribute("total", total);
	
		
		
		req.getRequestDispatcher("customer/fillPassengers.jsp").include(req, resp);
		
		
		
	}

}
